const { defineConfig } = require('@vue/cli-service')
const path = require('path')

// 开启gzip压缩，按需引用
// const CompressionWebpackPlugin = require('compression-webpack-plugin')
// 开启gzip压缩，按需写入
// const productionGzipExtensions = /\.(js|css|json|txt|html|icon|svg)(\?>*)?$/i
// 打包分析
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin

// 是否是生产环境
// const isProduction = ['production', 'prod'].includes(process.env.NODE_ENV)
const resolve = dir => path.join(__dirname, dir)

// 配置预解析的内容
// const sourcePrefetch = {
//   // dns预解析
//   dns: ['http://jquery.cdn.com'],
//   // 字体预解析
//   fonts: [`/static/fonts/SourceHanSansCN-Regular.woff2`]
// }

module.exports = defineConfig({
  // 基本路径
  publicPath: './',
  lintOnSave: false,
  transpileDependencies: true,

  // 生产环境是否生成sourceMap 文件，一般不建议打开
  productionSourceMap: process.env.NODE_ENV !== 'production',

  // 文件输出目录
  outputDir: 'dist',

  // webpack-dev-server相关配置
  devServer: {
    open: true
    // proxy: {
    //   '/tx': {
    //     target: 'https://apis.map.qq.com/',
    //     changeOrigin: true,
    //     pathRewrite: {
    //       '^/tx': ''
    //     }
    //   }
    // }
  },
  chainWebpack: config => {
    const types = ['vue-modules', 'vue', 'normal-modules', 'normal']
    types.forEach(type => addStyleResource(config.module.rule('less').oneOf(type)))
    config.plugins.delete('named-chunks')

    // 修复HMR
    config.resolve.symlinks(true)
    config.resolve.alias.set('@', resolve('src')).set('_c', resolve('src/components')).set('_v', resolve('src/views'))
  },
  configureWebpack: {
    plugins: [new BundleAnalyzerPlugin()],
    optimization: {
      splitChunks: {
        cacheGroups: {
          'vendors-base': {
            name: 'vendors-base',
            test: /[\\/]node_modules[\\/](vue|axios|vuex)/,
            chunks: 'all',
            priority: 10,
            enforce: true
          }
        }
      }
    }
  }
})
function addStyleResource(rule) {
  rule
    .use('style-resource')
    .loader('style-resources-loader')
    .options({
      patterns: [
        path.resolve(__dirname, './src/styles/variables.less') // 需要全局导入的less
      ]
    })
}
